import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import {SystemRouters, CmsRouters} from '@/router'
import {setTitle} from '@/utils'
import {getStore} from '@/utils/store'
import store from '@/store'
import { getToken, hasPagePermission } from "@/utils/auth";

const whiteList = ['/login', '/401', '/404', '/500'] //不重定向的白名单

router.beforeEach((to, from, next) => {
    NProgress.configure({ showSpinner: false });
    NProgress.start() //开启NProgress进度条
    setTitle(to.name)

    //判断浏览器Session Storage中是否存在Token，Token不存在全部路由到login页面
    if(getToken()) {

        if(to.path === '/login') {  //如果token存在并且当前页面是login则直接重定向到主页
            router.replace('/')
        } else {
            //用户刷新了页面，vuex中保存的数据丢失，需重新设置上去，并生成路由表
            if(store.getters.user == null) {
                store.dispatch('SetUserData').then(() => {

                    // 生成可访问的路由表
                    let asyncRouter = []
                    let ROUTER_TYPE = getStore({ name: 'ROUTER_TYPE' });
                    if(ROUTER_TYPE === 'CMS') {
                        asyncRouter = CmsRouters
                    } else {
                        asyncRouter = SystemRouters
                    }
                    store.dispatch('GeneratorRouters', asyncRouter).then(() => {
                        router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                        next(...to)
                    })

                    next(...to) // hack方法 确保addRoutes已完成
                })
            } else {
                if (whiteList.indexOf(to.path) !== -1) { //在免登录白名单中，直接进入
                    next()
                } else { //验证权限
                    if(hasPagePermission(to.meta.auth)) {
                        next()
                    } else {
                        next({ path: '/401' })
                    }
                }
            }
        }
    } else {
        if(whiteList.indexOf(to.path) !== -1) { //在免登录白名单中，直接进入
            next()
        } else {
            //重定向到登录页
            if(router.history.current.path !== '/login' && router.history.current.path !== '/') {
                window.location.reload()    //刷新，清空路由表数据
            } else {
                router.replace('/login')
            }
            NProgress.done()    //结束NProgress进度条
        }
    }
})

router.afterEach(() => {
    NProgress.done() //结束NProgress进度条
})